package com.ruicar.afs.cloud.parameter.commom.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.parameter.commom.condition.AddressParamCondition;
import com.ruicar.afs.cloud.parameter.commom.condition.AppAddressTitleCondition;
import com.ruicar.afs.cloud.parameter.commom.condition.AreaValueCondition;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysAddressParam;
import com.ruicar.afs.cloud.parameter.commom.service.TsysAddressParamService;
import com.ruicar.afs.cloud.parameter.commom.utils.ParamConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.ruicar.afs.cloud.parameter.commom.utils.ParamConstants.*;


/**
 * @Description:地址区域控制层
 * @Author:jihuigeng
 * @Date:2020/5/13 17:52
 * @Version: V1.0
 **/
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/common")
@Api("地区信息管理")
public class AddressParamController {

    private final TsysAddressParamService service;

    /**
     * 获取地区信息
     *
     * @param condition
     * @return
     */
    @Transactional
    @PostMapping(value = "/getAddressList")
    @ApiOperation(value = "获取数据")
    public IResponse<List<TsysAddressParam>> getAddressList(@RequestBody AddressParamCondition condition) {
        List<TsysAddressParam> list = service.list(Wrappers.<TsysAddressParam>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getUpperCode()), TsysAddressParam::getUpperCode, condition.getUpperCode())
                .eq(StringUtils.isNotEmpty(condition.getLevel()), TsysAddressParam::getAddrLevel, condition.getLevel()).orderByAsc(TsysAddressParam::getValue));
        //返回数据
        return new IResponse<List<TsysAddressParam>>().setData(list);
    }

    @Transactional
    @PostMapping(value = "/getAddressByCode")
    @ApiOperation(value = "获取数据")
    public IResponse<TsysAddressParam> getAddressByCode(@RequestBody AddressParamCondition condition) {
        TsysAddressParam list = service.getOne(Wrappers.<TsysAddressParam>query().lambda().eq(TsysAddressParam::getValue,condition.getValue()));
        //返回数据
        return new IResponse<TsysAddressParam>().setData(list);
    }

    /**
     * 获取地区信息
     *
     * @param areaValueCondition
     * @return
     */
    @Transactional
    @PostMapping(value = "/getAreaValueById")
    @ApiOperation(value = "获取数据")
    public IResponse<List<TsysAddressParam>> getAreaValueById(@RequestBody AreaValueCondition areaValueCondition) {
        String[] idArray = areaValueCondition.getId().split(",");
        List list = new ArrayList<>();
        for (int j = 0; j < idArray.length; j++) {
            Long id = Long.valueOf(idArray[j].toString());
            list.add(id);
        }
        List<TsysAddressParam> tsysAddressParams = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
            TsysAddressParam tsysAddressParam = service.getOne(Wrappers.<TsysAddressParam>query().lambda()
                    .eq(TsysAddressParam::getValue, list.get(i)));
            tsysAddressParams.add(tsysAddressParam);
        }
        return IResponse.success(tsysAddressParams);
    }

    /**
     * 获取地区树状图
     *
     * @return
     */
    @Transactional
    @PostMapping(value = "/getAddressTree")
    @ApiOperation(value = "获取省市区树状图")
    public IResponse<List<TsysAddressParam>> getAddressTree() {
        List<TsysAddressParam> list = service.list(Wrappers.<TsysAddressParam>query().lambda().orderByAsc(TsysAddressParam::getValue));
        //返回数据
        List<TsysAddressParam> addressList = new ArrayList<>();
        list.forEach(addressParam -> {
            addressParam.setTitle(addressParam.getLabel());
            addressList.add(addressParam);
        });
        //默认查询层级最上层0层，表示全国区域
        int level = 0;
        List<TsysAddressParam> permissions = addressList.stream().filter(addressParam -> ParamConstants.ADDRESS_LEVEL.equals(addressParam.getAddrLevel())).collect(Collectors.toList());
        permissions.forEach(addressParam -> {
            findAddressParam(addressParam, addressList, level);
        });
        return new IResponse<List<TsysAddressParam>>().setData(permissions);
    }

    private void findAddressParam(TsysAddressParam addressParam, List<TsysAddressParam> tsysAddressParam, int level) {
        List<TsysAddressParam> children = tsysAddressParam
                .stream()
                .filter(child -> addressParam.getValue().equals(child.getUpperCode()))
                .collect(Collectors.toList());
        children.forEach(child -> {
            //层级+1
            child.setAddrLevel(level + 1 + "");
            findAddressParam(child, tsysAddressParam, level + 1);
        });
        addressParam.setChildren(children);
    }


    /**
     * 规则原子使用获取地区信息
     *
     * @param condition
     * @return
     */
    @Transactional
    @PostMapping(value = "/getAddressListByUpperCode")
    @ApiOperation(value = "规则原子使用")
    public IResponse<Object> getAddressListByUpperCode(@RequestBody AddressParamCondition condition) {
        List<TsysAddressParam> list = service.list(Wrappers.<TsysAddressParam>query().lambda()
                .eq(StringUtils.isNotEmpty(condition.getUpperCode()), TsysAddressParam::getUpperCode, condition.getUpperCode())
                .eq(StringUtils.isNotEmpty(condition.getLevel()), TsysAddressParam::getAddrLevel, condition.getLevel()));
        //返回 title：value：json对象数组
        List<TsysAddressParam> addressList = new ArrayList<>();
        list.forEach(addressParam -> {
            addressParam.setTitle(addressParam.getLabel());
            addressList.add(addressParam);
        });
        return new IResponse<Object>().setData(addressList);
    }


    /**
     * 获取地区信息 app
     *
     * @param titleCondition
     * @return
     */
    @RequestMapping(value = "/getAppAddressListTitle", method = RequestMethod.POST)
    @ApiOperation(value = "app省市翻译")
    public IResponse<List<TsysAddressParam>> getAppAddressListTitle(@RequestBody AppAddressTitleCondition titleCondition) {
        if (titleCondition.getAppAddressTitle() == null && titleCondition.getAppAddressTitle().size() == 0) {
            return IResponse.fail("查询失败,查询参数异常");
        }
        List<AppAddressTitleCondition> conditionList = new ArrayList<>();
        for (AppAddressTitleCondition condition : titleCondition.getAppAddressTitle()) {
            AppAddressTitleCondition appAddressTitleCondition = new AppAddressTitleCondition();
            ////省份查询
            TsysAddressParam param = service.getOne(Wrappers.<TsysAddressParam>query().lambda()
                    .eq(TsysAddressParam::getValue, condition.getProvince()).eq(TsysAddressParam::getAddrLevel, ADDRESS_LEVEL_ONE));
            if (param != null) {
                appAddressTitleCondition.setProvinceTitle(param.getLabel());
                appAddressTitleCondition.setProvince(condition.getProvince());
            }


            //城市查询
            TsysAddressParam addressParam = service.getOne(Wrappers.<TsysAddressParam>query().lambda()
                    .eq(TsysAddressParam::getValue, condition.getCity()).eq(TsysAddressParam::getAddrLevel, ADDRESS_LEVEL_TWO));
            if (addressParam != null) {
                appAddressTitleCondition.setCityTitle(addressParam.getLabel());
                appAddressTitleCondition.setCity(condition.getCity());
            }
            conditionList.add(appAddressTitleCondition);
        }
        return IResponse.success(conditionList);
    }
}
